package com.mashibing.mall.ware.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mashibing.common.constant.WareConstant;
import com.mashibing.common.exception.BusinessException;
import com.mashibing.mall.ware.entity.PurchaseDetailEntity;
import com.mashibing.mall.ware.service.PurchaseDetailService;
import com.mashibing.mall.ware.service.WareSkuService;
import com.mashibing.mall.ware.vo.MergeVO;
import com.mashibing.mall.ware.vo.PurchaseDoneVO;
import com.mashibing.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mashibing.common.utils.PageUtils;
import com.mashibing.common.utils.Query;

import com.mashibing.mall.ware.dao.PurchaseDao;
import com.mashibing.mall.ware.entity.PurchaseEntity;
import com.mashibing.mall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 采购信息 Service 实现类
 */
@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Resource
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 采购信息 - 分页(查询采购单的状态为 新建 或者 已分配 的采购单信息)
     */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        // 添加查询的条件
        queryWrapper.eq("status",0).or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 采购信息 - 合并
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer merge(MergeVO mergeVO) {

        // 获取 采购单 id
        Long purchaseId = mergeVO.getPurchaseId();

        // 如果采购单 id 为空
        if (purchaseId == null) {

            // 新建一个 采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // 整合采购需求单
        List<Long> items = mergeVO.getItems();
        final long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntityList = items.stream().map(item -> {

            // 构建采购需求明细
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            // 更新每一条 需求单的 采购单 id
            detailEntity.setId(item);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntityList);

        // 更新采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        return 0;
    }

    /**
     * 采购信息 - 领取采购单
     * 传入参数：ids
     * [2,3,4]
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void receive(List<Long> ids) {

        // 根据采购单 id 查询采购单
        List<PurchaseEntity> purchaseEntityList = ids.stream().map(this::getById)
            .filter(purchaseEntity -> {

                // 如果采购单的状态不是 新建 或者 已分配，则抛出异常
                if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() ||
                        purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {

                    return true;
                }
                throw new BusinessException("采购单状态不正确");
            }).peek(purchaseEntity -> {

                // 设置更新时间
                purchaseEntity.setUpdateTime(new Date());

                // 设置采购单的状态为已领取
                purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());

                }).collect(Collectors.toList());

        // 更新采购单的状态
        this.updateBatchById(purchaseEntityList);

        // 遍历采购单 ids
        for (Long id : ids) {

            // 根据采购单 id 查询采购需求明细
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(id);

            List<PurchaseDetailEntity> purchaseDetailEntityList = detailEntities.stream().map(item -> {

                // 构建采购需求明细
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

                // 更新每一条 需求单的 采购单 id、状态
                detailEntity.setId(item.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());

                return detailEntity;
            }).collect(Collectors.toList());

            // 批量更新采购需求明细
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        }
    }

    /***
     * 采购信息 - 完成采购
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void done(PurchaseDoneVO vo) {

        // 采购单编号
        Long id = vo.getId();

        // 2.改变采购项的状态
        // 采购项状态,默认为 完成
        Boolean flag = true;

        // 获取所有采购明细列表
        List<PurchaseItemDoneVO> items = vo.getItems();

        // 构建待更新的采购明细
        List<PurchaseDetailEntity> list = CollectionUtil.newArrayList();

        // 遍历采购明细列表
        for (PurchaseItemDoneVO item : items) {

            // 构建代更新的采购明细
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();

            // 如果采购状态为【采购失败】，则将 flag 置为 false
            if (WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode() == item.getStatus()) {
                flag = false;
                detailEntity.setStatus(item.getStatus());
            } else {

                // 设置采购状态为【采购完成】
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());

                // 3.将采购成功的采购项进入库操作
                // 根据采购明细 id 查询采购明细
                PurchaseDetailEntity purchaseDetailEntity = purchaseDetailService.getById(item.getItemId());

                System.out.println(purchaseDetailEntity);

                // 更新库存
                wareSkuService.addStock(purchaseDetailEntity.getSkuId(), purchaseDetailEntity.getWareId(), purchaseDetailEntity.getSkuNum());
            }

            // 设置采购明细的 id
            detailEntity.setId(item.getItemId());

            // 添加到待更新的采购明细列表
            list.add(detailEntity);
        }

        // 批量更新采购明细
        purchaseDetailService.updateBatchById(list);

        // 1.改变采购单的状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);

        // 如果 flag 为 false，则采购单状态为【采购失败】
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());

        // 更新更新时间
        purchaseEntity.setUpdateTime(new Date());

        // 更新采购单
        this.updateById(purchaseEntity);
    }
}
